import { getDictionary } from '@/dictionaries/dictionaries';
import ProfileClient from './ProfileClient';
import { getServerSession } from 'next-auth';
import { authOptions } from '@/auth.config';
import { revalidatePath } from 'next/cache';
import { getUserByOpenid, updateUser,getAllUsers } from '@/lib/userService';
import { getCampuses } from '@/lib/campusService';
import { getCourts } from '@/lib/courtsService';
import { getClientCoursePackages } from '@/lib/coursePackagesService';
async function updatePhone(phone) {
  'use server'

  const session = await getServerSession(authOptions);
  if (!session) {
    throw new Error('Unauthorized');
  }
  console.log("updatePhone session", session);
  try {
    await updateUser(session.user.id, { phone_number: phone });

    revalidatePath('/profile');
    return { success: true };
  } catch (error) {
    console.error('Failed to update phone:', error);
    throw new Error('Failed to update phone');
  }
}

async function updateName(name) {
  'use server'
  try {
    const session = await getServerSession(authOptions)
    if (!session?.user?.id) {
      return { success: false, message: '未登录' }
    }

    await updateUser(session.user.id, { name })

    revalidatePath('/profile')
    return { success: true }
  } catch (error) {
    console.error('Failed to update name:', error)
    return { success: false, message: '更新失败' }
  }
}

export default async function ProfilePage() {
  const lang = 'zh'
  const dict = await getDictionary(lang);
  const session = await getServerSession(authOptions);

  if (!session) {
    redirect('/login');
  }
  const user = await getUserByOpenid(session.user.openid);
  user.picture = session.user?.picture || session.user?.image;
  const campuses = await getCampuses({ status: 'active' });
  const courts = await getCourts({ status: 'active' });
  const coaches = await getAllUsers({ role: 'coach' });
  const clients = await getAllUsers({ role: 'client' });
  const clientCoursePackages = await getClientCoursePackages(user.id, { status: 'active' });
  return <ProfileClient dict={dict} user={user}
    coaches={coaches}
    clients={clients}
    updatePhone={updatePhone}
    updateName={updateName}
    campuses={campuses}
    courts={courts}
    clientCoursePackages={clientCoursePackages}
  />;
}
